package com.kangyi.user.aspect;

import com.kangyi.user.annotation.AutoFill;
import com.kangyi.constant.AutoFillConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Blank
 * @version 3.0
 * 自定义切面，实现公共字段自动填充处理逻辑，支持 List 批量填充
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 切入点
     */
    @Pointcut("execution(* com.kangyi.user.mapper.*.*(..)) && @annotation(com.kangyi.user.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    /**
     * 前置通知，在通知中进行公共字段的赋值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行公共字段自动填充");

        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }

        // 赋值公共字段
        LocalDateTime now = LocalDateTime.now();
        Integer currentId = BaseContext.getCurrentId();

        if (currentId == null) {
            log.warn("当前用户 ID 为空，无法进行公共字段自动填充");
            return;
        }

        for (Object arg : args) {
            if (arg instanceof List<?>) {
                // 处理 List<T> 类型
                List<?> entityList = (List<?>) arg;
                if (!entityList.isEmpty()) {
                    for (Object entity : entityList) {
                        fillCommonFields(entity, operationType, now, currentId.intValue());
                    }
                }
            } else {
                // 处理单个实体对象
                fillCommonFields(arg, operationType, now, currentId.intValue());
            }
        }
    }

    /**
     * 统一处理字段填充逻辑
     */
    private void fillCommonFields(Object entity, OperationType operationType, LocalDateTime now, Integer currentId) {
        if (entity == null) {
            return;
        }

        try {
            if (operationType == OperationType.INSERT) {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Integer.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Integer.class);

                setCreateTime.invoke(entity, now);
                setCreateUser.invoke(entity, currentId);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentId);
            } else if (operationType == OperationType.UPDATE) {
                Method setUpdateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod("setUpdateUser", Integer.class);

                //通过反射为对象属性赋值
                setUpdateTime.invoke(entity,now);
                setUpdateUser.invoke(entity,currentId);
            }
        } catch (Exception e) {
            log.error("自动填充字段失败", e);
        }
    }

    /**
     * 通过反射设置字段值
     */
    private void setField(Object entity, String methodName, Class<?> paramType, Object value) {
        try {
            Method method = entity.getClass().getDeclaredMethod(methodName, paramType);
            method.invoke(entity, value);
        } catch (NoSuchMethodException ignored) {
            log.warn("实体 {} 缺少方法 {}", entity.getClass().getSimpleName(), methodName);
        } catch (Exception e) {
            log.error("无法设置字段: {}", methodName, e);
        }
    }
}